<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程名"
          clearable
          @keyup.enter.native="handleQuery"
        />
<!--         @keyup.enter.native="handleQuery" 加入回车功能-->
      </el-form-item>
      <el-form-item label="老师名" prop="tname">
        <el-input
          v-model="queryParams.tname"
          placeholder="请输入老师名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['classes:classes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['classes:classes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['classes:classes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['classes:classes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
<!--      <el-table-column label="课程图片" align="center" prop="image" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <image-preview :src="scope.row.image" :width="50" :height="50"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="image" label="课程图片" align="center" width="100">
        <template slot-scope="{ row }">
          <el-image style="width: 50px; height: 50px; border:none;cursor: pointer;" :src="getImage(row.image)" :preview-src-list="[ `/common/download?name=${row.image}` ]" >
            <div slot="error" class="image-slot">
              <img src="src/assets/images/img.png" style="width: auto; height: 40px; border:none;" >
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="课程名" align="center" prop="name" />
      <el-table-column label="老师名" align="center" prop="tname" />
<!--      <el-table-column label="描述" align="center" prop="description" width="150"/>-->
        <el-table-column label="描述" align="center" prop="description" width="150">
          <template slot-scope="scope">
            <div v-if="!scope.row.showFullDescription">
              {{ scope.row.description.substring(0, 50) }}
              <span v-if="scope.row.description.length > 50"
                    @click="toggleDescription(scope.row, true)">
          ...展开
        </span>
            </div>
            <div v-else>
              {{ scope.row.description }}
              <span @click="toggleDescription(scope.row, false)">
          收起
        </span>
            </div>
          </template>
        </el-table-column>

      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" prop="registrationTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registrationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名截止时间" align="center" prop="deadTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['classes:classes:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['classes:classes:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="老师ID" prop="teacherId">-->
<!--          <el-input v-model="form.teacherId" placeholder="请输入老师ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="课程名" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
<!--        <el-form-item label="老师名" prop="tname">-->
<!--          <el-input v-model="form.tname" placeholder="请输入老师名" />-->
<!--        </el-form-item>-->
        <el-form-item label="老师名字:" prop="teacherId" >
          <el-select v-model="form.teacherId" placeholder="请选择">
            <el-option v-for="item in teachers" :key="item.userId" :label="item.nickName" :value="item.userId">{{item.nickName}}</el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="课程类型" prop="tagsName">-->
<!--          <el-input v-model="form.tagsName" placeholder="请输入课程类型" />-->
<!--        </el-form-item>-->
        <el-form-item label="课程类型:" prop="tagsId">
          <el-select v-model="form.tagsId" placeholder="请选择">
            <el-option v-for="item in tags" :key="item.id" :label="item.subject" :value="item.id">{{item.subject}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述">
          <editor v-model="form.description" :min-height="192"/>
        </el-form-item>
        <el-form-item label="课程图片" prop="image" class="uploadImg">
<!--          <image-upload v-model="form.image"/>-->
          <el-upload class="image-uploader" action="/dev-api/common/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :on-change="onChange" ref="upload">
            <img v-if="imageUrl" :src="imageUrl" class="image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
<!--        <el-form-item label="课程图片" prop="image">-->
<!--          <image-upload v-model="form.image"/>-->
<!--          <el-image style="width: auto; height: 40px; border:none;cursor: pointer;" :src="getImage(row.image)" :preview-src-list="[ `/common/download?name=${row.image}` ]" >-->
<!--            <div slot="error" class="image-slot">-->
<!--              <img src="../../../assets/images/img.png" style="width: auto; height: 40px; border:none;" >-->
<!--            </div>-->
<!--          </el-image>-->
<!--        </el-form-item>-->
        <el-form-item label="课程开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="课程结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名开始时间" prop="registrationTime">
          <el-date-picker clearable
            v-model="form.registrationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择报名时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名截止时间" prop="deadTime">
          <el-date-picker clearable
            v-model="form.deadTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择报名截止时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {listClasses, getClasses, delClasses, addClasses, updateClasses,} from "@/api/classes/classes"
import { download } from  "@/api/common";
import {getAllTagsName} from "@/api/tags/tags"
// import {getAllTeacherName} from "@/api/userss/users"
import {getAllTeacherName} from "@/api/system/user"

const regex = /<p>(.*?)<\/p>/g;
export default {
  name: "Classes",
  data() {
    return {
      imageUrl: '',
      teachers: [],
      tags: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程管理表格数据
      classesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherId: null,
        price: null,
        name: null,
        tname: null,
        tagsName: null,
        tagsId: null,
        status: null,
        description: null,
        image: null,
        startTime: null,
        endTime: null,
        registrationTime: null,
        deadTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        teacherId: [
          { required: true, message: "老师ID不能为空", trigger: "blur" }
        ],
        tagsId: [
          { required: true, message: "课程类型ID不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList();
    getAllTeacherName().then(res=>{
      console.log("/*/*/*/**/*/**/*/*/*/*/*/*/11111")
      // console.log(res.data)
      this.teachers = res.data
      console.log(this.teachers)
    });
    getAllTagsName().then(res=>{
      this.tags = res.data
      console.log("/*/*/*/**/*/**/*/*/*/*/*/*/")
      console.log(this.tags)
      //this.ruleForm.tags = this.arr
    })
  },
  methods: {
    /** 查询课程管理列表 */
    // getList() {
    //   this.loading = true
    //   listClasses(this.queryParams).then(response => {
    //     // let match
    //     let reg = /<[^>]+>/gi;
    //     console.log(response)
    //     this.classesList = response.rows
    //     this.total = response.total
    //     this.loading = false
    //     this.classesList.forEach(item=>{
    //       if (item.description){
    //         item.description = item.description.replace(reg,"");
    //       }
    //     })
    //   })
    // },
    getList() {
      this.loading = true;
      listClasses(this.queryParams).then(response => {
        let reg = /<[^>]+>/gi;
        this.classesList = response.rows;
        this.total = response.total;

        // 处理课程列表数据
        this.classesList.forEach(item => {
          if (item.description) {
            item.description = item.description.replace(reg, "");
          }
          // 确保每个项目都有 showFullDescription 属性
          this.$set(item, 'showFullDescription', false);
        });

        this.loading = false;
      });
    },
    // 处理展开/收起状态的方法
    toggleDescription(item, show) {
      // 使用 Vue.set 确保响应式更新
      this.$set(item, 'showFullDescription', show);
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    onChange (file) {
      if(file){
        const suffix = file.name.split('.')[1];
        const size = file.size / 1024 / 1024 < 2;
        if(['png','jpeg','jpg'].indexOf(suffix) < 0){
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！');
          this.$refs.upload.clearFiles();
          return false
        }
        if(!size){
          this.$message.error('上传文件大小不能超过 2MB!');
          return false
        }
        return file
      }
    },
    handleAvatarSuccess (response, file, fileList) {
      // console.log(66666)
      // 拼接down接口预览
      // if(response.code === 0 && response.msg === '未登录'){
      //   window.top.location.href = '../login/login.html'
      // }else{
      //   this.imageUrl = `/common/download?name=${response.data}`;

      // console.log("11111111111")
      console.log(response)
      this.form.image = response.data
        // this.form.image =  response.data
      if (response.code==200){
        download(response.data).then(res=>{
          // console.log(response)
          // console.log(res)
          this.imageUrl="/dev-api/common/download?name="+response.data
        })
      // }
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teacherId: null,
        price: null,
        name: null,
        tname: null,
        tagsName: null,
        tagsId: null,
        status: null,
        description: null,
        image: null,
        startTime: null,
        endTime: null,
        registrationTime: null,
        deadTime: null
      }
      this.imageUrl = null;
        this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加课程管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getClasses(id).then(response => {
        console.log(response)
        this.form = response.data
        this.open = true
        this.title = "修改课程管理"
        this.imageUrl = '/dev-api/common/download?name='+response.data.image
      })
    },
    /** 提交按钮 */
    submitForm() {
      // this.form.tagsId = this.form.tagsName.id
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.imageUrl){
            this.$message.error('请上传图片');
            return
          }
          if (this.form.id != null) {
            updateClasses(this.form).then(response => {
              // console.log(11111111)
              // console.log(this.form)
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addClasses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    getImage (image) {
      // console.log(image)
      // console.log(`/common/download?name=${image}`)
      return `/dev-api/common/download?name=${image}`

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除课程管理编号为"' + ids + '"的数据项？').then(function() {
        return delClasses(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('classes/classes/export', {
        ...this.queryParams
      }, `classes_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.image-uploader{
  height: 100px;
}
.image{
  width: 80px;
  height: 80px;
}
.el-upload el-upload--text{
  width: 100px;
  height: 100px;
}
.image-uploader-icon{
  width: 90px;
  height: 90px;
}
.image-uploader-icon::before{
  width: 100%;
  height: 100%;
}

</style>
